package 面试题16_数值的整数次方.类似斐波那契数列实现.循环实现;

/**
 * @Author ：xu_xiaofeng.
 * @Date ：Created in 22:10 2021/2/14
 * @Description：
 */
public class Solution {

    /**
     * 有误，尚未修改
     * @param x
     * @param n
     * @return
     */

    public double myPow(double x, int n) {
        // 特殊输入：0的负数次幂
        if (isEqual(x, 0.0)) return 0;

        int absExponent = Math.abs(n);

        double res = PowerWithUnsignedExponent(x, absExponent);

        if (n < 0) {
            res = 1 / res;
        }

        return res;
    }

    double PowerWithUnsignedExponent(double base, int exponent) {

        double result = base;

        while (exponent > 0) {

            if (exponent == 1) {
                return result;
            }

            result *= result;

            exponent = exponent >> 1;
        }

        if ((exponent & 1) == 1) {
            return result * base;
        }

        return result;
    }

    boolean isEqual(double num_1, double num_2) {
        double absResult = Math.abs(num_1 - num_2);

        return absResult < 1e-6;
    }
}
